import React from 'react';
import { connect } from 'react-redux';
import BaseComponent from '../../components/common/baseComponent.js';
import Button from '../../components/common/button';
import CouponSelectModal from '../../components/coupon/couponSelectModal';
// import { getQueryParam } from '../../utils/url';
import CouponCell from '../../components/coupon/couponCell';
import toast from '../../utils/toast';
import CouponAlertModal from '../../components/coupon/couponAlertModal';
import { debounced } from '../../utils/func';
import Loading from '../../components/common/loading';

@connect(({
  coupon,
  pay,
  loading,
  user,
}) => {
  const couponList = coupon.get('payCouponList');
  const balancePay = pay.getIn(['payMode', 'balance']);
  const cashPay = pay.getIn(['payMode', 'cash']);
  const payModeList = balancePay.get('show') ? cashPay.insert(0, balancePay) : cashPay;
  const showBalance = balancePay.get('show');
  const showCoupon = pay.getIn(['payMode', 'showCoupon']) && couponList.size > 0 && payModeList.filter(pm => pm.get('selected')).every(pm => pm.get('useCoupon'));
  return {
    canOnlyUseCoupon: pay.getIn(['payMode', 'canOnlyCoupon']),
    showBalance,
    balancePay,
    cashPay,
    showCoupon,
    couponList,
    payModeList,
    balance: user.getIn(['account', 'balance']),
    maxSelect: coupon.get('maxSelect'),
    disabled: ['pay/fetchPayModeIfNeeded', 'coupon/fetchAndCalPayCoupon'].some(action => loading.effects[action]),
    loading: ['refuel/refuel', 'pay/prePay', 'pay/doPay'].some(action => loading.effects[action]),
    order: pay.get('order'),
  };
})
class Pay extends BaseComponent {
  state = {
  }
  componentDidMount() {
    const { order } = this.props;
    if (!order) {
      return this.props.history.goBack();
    }

    this.props.dispatch({
      type: 'pay/initPay',
      payload: {
        money: order.get('actAmount'),
        modeParams: {
          source: window.source,
        },
      },
    });
  }
  getTitle = () => {
    let title = '支付金额';
    const { payModeList } = this.props;
    const selectedList = payModeList.filter(pm => pm.get('selected'));
    let type;
    if (selectedList.size === 1) {
      type = selectedList.getIn([0, 'id']);
    } else if (selectedList.size > 1) {
      type = selectedList.find(pm => pm.get('id') !== 1).get('id');
    }
    switch (type) {
      case 1:
        title = '还需支付金额';
        break;
      case 2:
        title = '微信支付金额';
        break;
      case 3:
        title = '支付宝支付金额';
        break;
      default:
        break;
    }
    return title;
  }

  clickPay = debounced(() => {
    console.log('click pay');
    const { order } = this.props;

    const money = order.get('actAmount');
    const {
      payModeList, couponList, canOnlyUseCoupon, showCoupon,
    } = this.props;
    const selectedList = payModeList.filter(pm => pm.get('selected'));
    const selectedCouponList = couponList.filter(coupon => coupon.get('selected'));
    const isTmall = selectedCouponList.some(coupon => coupon.isTmall());
    const tmallAmount = selectedCouponList.filter(coupon => coupon.isTmall()).reduce((amount, coupon) => {
      return amount + coupon.get('giftAmount');
    }, 0) / 100;
    if (!canOnlyUseCoupon && selectedList.size === 0) {
      toast('请选择支付方式');
    } else if (canOnlyUseCoupon && selectedCouponList.size === 0 && selectedList.size === 0) {
      toast('请选择支付方式或至少选择一张电子券');
    } else if (isTmall && showCoupon) {
      if (Number(tmallAmount) < Number(money)) {
        this.alert.show('订单金额大于加油券面额不可使用');
      } else if (Number(tmallAmount) > Number(money)) {
        this.alert.show('订单金额小于加油券面额，差额部分不退还');
      } else {
        this.doPay();
      }
    } else {
      this.doPay();
    }
  }, 300)

  closeAlert = () => {
    const { couponList } = this.props;
    const { money } = this.state;
    const selectedCouponList = couponList.filter(coupon => coupon.get('selected'));
    const tmallAmount = selectedCouponList.filter(coupon => coupon.isTmall()).reduce((amount, coupon) => {
      return amount + coupon.get('giftAmount');
    }, 0) / 100;
    this.alert.close();
    if (Number(tmallAmount) > Number(money)) {
      this.doPay();
    }
  }

  doPay = () => {
    const { payModeList, couponList, showCoupon, order } = this.props;
    const selectedList = payModeList.filter(pm => pm.get('selected'));
    const selectedCouponList = couponList.filter(coupon => coupon.get('selected'));
    const payModes = [];
    let prePayMode;
    if (selectedCouponList.size > 0 && showCoupon) {
      payModes.push(3);
    }
    if (selectedList.some(pm => pm.get('type') === 'balance')) {
      payModes.push(1);
    }
    if (selectedList.some(pm => pm.get('type') === 'cash')) {
      payModes.push(2);
      prePayMode = selectedList.find(pm => pm.get('type') === 'cash').getPayMode();
    }

    this.props.dispatch({
      type: 'pay/prePay',
      payload: {
        type: 'ESCORT_BUY_MENBER',
        orderType: 3,
        payMode: prePayMode,
        payModes,
        payOrderNo: order.get('orderNo'),
        callBackUrl: `${window.location.href.split('#')[0]}#/escort/result?type=insurance`,
      },
    });
  }

  showCouponModal = () => {
    this.props.dispatch({
      type: 'coupon/sortCouponList',
    });
    this.modal.show();
  }

  selectCoupon = (coupon) => {
    const { money } = this.state;
    this.props.dispatch({
      type: 'coupon/selectRefuelCoupon',
      payload: {
        selectCoupon: coupon,
        number: money,
      },
    });
  }

  selectCouponDone = () => {
    this.modal.close();
  }

  selectPayMode = (pm) => {
    this.props.dispatch({
      type: 'pay/selectPayMode',
      payload: { payMode: pm },
    });
  }

  render() {
    const {
      couponList,
      maxSelect,
      payModeList,
      showCoupon,
      loading,
      disabled,
      balance,
      balancePay,
      order,
    } = this.props;

    if (!order) {
      return <Loading />;
    }

    const money = order.get('actAmount');
    console.log('------', payModeList.toJS());
    const payCells = payModeList.map((pm, index) => {
      let textView;
      if (pm.get('type') === 'balance') {
        textView = <div className="text">可用余额&#65509;{balance}</div>;
      }
      return (
        <div className="pay-cell" key={index} onClick={() => this.selectPayMode(pm)}>
          <img src={pm.getIcon()} alt="" className="icon" />
          <div className="title">{pm.get('name')}</div>
          {textView}
          <i className={`iconfont icon-checkbox ${pm.get('selected') ? 'icon-checked' : 'icon-unchecked'}`} />
        </div>
      );
    });

    const selectedCouponList = couponList.filter(coupon => coupon.get('selected'));

    let couponView;

    if (showCoupon) {
      const couponCells = selectedCouponList.map((coupon, index) => {
        return <CouponCell coupon={coupon} key={index} />;
      });
      couponView = (
        <div className="coupon-view" onClick={this.showCouponModal}>
          <div className="title-row">
            <div className="title">加油优惠券</div>
            <p className="text">已选择<span className="num">{selectedCouponList.size}</span>张</p>
            <i className="iconfont icon-arrow" />
          </div>
          {couponCells}
        </div>
      );
    }

    const couponDis = showCoupon ? Math.min(selectedCouponList.reduce((total, coupon) => {
      return total + (coupon.get('giftAmount') / 100);
    }, 0), money) : 0;

    let couponMoney;
    if (couponDis > 0) {
      couponMoney = <p className="dis">优惠券抵扣{couponDis.toFixed(2)}元</p>;
    }

    let balanceMoney;
    if (balancePay && balancePay.get('selected')) {
      balanceMoney = (<p className="dis">鱿鱼账户支付{Math.min(money - couponDis, balance).toFixed(2)}元</p>);
    }

    return (
      <div className="pay">
        <div className="content">
          <div className="order-info-view">
            <div className="title">订单金额</div>
            <div className="money-row"><div className="unit">&#65509;</div><div className="money">{money}</div></div>
            {balanceMoney}
            {couponMoney}
          </div>
          <div className="pay-view">
            {payCells}
          </div>
          {couponView}
        </div>
        <Button title="立即支付" className="pay-btn" clickFunc={this.clickPay} loading={loading} disabled={disabled} />
        <CouponSelectModal
          ref={modal => this.modal = modal}
          couponList={couponList}
          selectFunc={this.selectCoupon}
          confirmFunc={this.selectCouponDone}
          maxSelect={maxSelect}
        />
        <CouponAlertModal ref={alert => this.alert = alert} closeFunc={this.closeAlert} />
      </div>
    );
  }
}

export default Pay;
